package com.wgke.bluetooth.utils;

import com.wgke.bluetooth.db.AppDatabase;
import com.wgke.bluetooth.db.CmdDao;
import com.wgke.bluetooth.db.CmdEntity;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Async {

    private ExecutorService executor;
    private CmdDao dao;
    private static Async instance;

    public static Async getInstance() {
        if (instance == null) {
            instance = new Async();
        }
        return instance;
    }

    public void await(Runnable runnable) {
        if (executor == null) {
            executor = Executors.newSingleThreadExecutor();
        }
        executor.execute(runnable);
    }

    public void awaitInsert(CmdEntity entity, Runnable runnable) {
        getExecutor().execute(() -> {
            getDao().insertAll(entity);
            if (runnable != null) {
                runnable.run();
            }
        });
    }

    public void awaitUpdate(CmdEntity entity, Runnable runnable) {
        getExecutor().execute(() -> {
            getDao().update(entity);
            if (runnable != null) {
                runnable.run();
            }
        });
    }

    private ExecutorService getExecutor() {
        if (executor == null) {
            executor = Executors.newSingleThreadExecutor();
        }
        return executor;
    }

    public CmdDao getDao() {
        if (dao == null) {
            dao = AppDatabase.getDatabase(CommonUtil.getContext()).cmdDao();
        }
        return dao;
    }

}
